package com.android.gl2jni.filter;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.Matrix;
import java.nio.FloatBuffer;

/**
 * Create time: 2018/9/26.
 */
public class SoulOutFilterProgram extends TextureFilterProgram {
  private int mAlphaLoc;
  private float mProgress = 0.0f;

  private int mFrames = 0;

  private static final int mMaxFrames = 15;

  private static final int mSkipFrames = 8;

  private static final String FRAGMENT =
      "#extension GL_OES_EGL_image_external : require\n" +
      " precision mediump float;\n" +
      " varying vec2 vTextureCoord;\n" +
      " uniform samplerExternalOES uTexture;\n" +
      " uniform float uAlpha;\n" +
      " void main(){\n" +
      "      gl_FragColor = vec4(texture2D(uTexture,vTextureCoord).rgb,uAlpha);\n" +
      " }";

  private float[] mMvpMatrix = new float[16];

  public SoulOutFilterProgram(Context context) {
    super(context, ProgramType.TEXTURE_EXT);
  }

  @Override
  protected void initProgram() {
    super.initProgram();
    mAlphaLoc = getUniformLocation("uAlpha");
  }

  @Override
  public void draw(float[] mvpMatrix, FloatBuffer vertexBuffer, int firstVertex, int vertexCount, int coordsPerVertex,
      int vertexStride, float[] texMatrix, FloatBuffer texBuffer, int textureId, int texStride) {
    GLES20.glEnable(GLES20.GL_BLEND);
    GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_DST_ALPHA);
    preDraw(textureId);
    Matrix.setIdentityM(mMvpMatrix, 0);
    mProgress = (float) mFrames / mMaxFrames;
    if (mProgress > 1f) {
      mProgress = 0f;
    }
    mFrames++;
    if (mFrames > mMaxFrames + mSkipFrames) {
      mFrames = 0;
    }
    float backAlpha = 1f;
    float alpha = 0f;
    if (mProgress > 0f) {
      alpha = 0.2f - mProgress * 0.2f;
      backAlpha = 1 - alpha;
    }
    setFloat(mAlphaLoc, backAlpha);
    updateMVPMatrix(mMvpMatrix);
    updateTexMatrix(texMatrix);
    updateAttrPosition(vertexBuffer, coordsPerVertex, vertexStride);
    updateAttrTextureCoord(texBuffer, texStride);
    onDraw(firstVertex, vertexCount);
    if (mProgress > 0f) {
      setFloat(mAlphaLoc, alpha);
      float scale = 1.0f + 1f * mProgress;
      Matrix.scaleM(mMvpMatrix, 0, scale, scale, scale);
      updateMVPMatrix(mMvpMatrix);
      onDraw(firstVertex, vertexCount);
    }
    afterDraw();
    GLES20.glDisable(GLES20.GL_BLEND);
  }

  @Override
  protected String getFragmentShaderSourceEXT() {
    return FRAGMENT;
  }
}
